<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-alert
        title="注意:只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
      >
      </el-alert>
      <!-- checkStrictly: true, -->
      <p>
        请选择商品分类:
        <el-cascader
          v-model="selectedKeys"
          :options="cateList"
          clearable
          :props="{
            expandTrigger: 'hover',
            label: 'cat_name',
            value: 'cat_id'
          }"
          @change="handleCascaderChange"
        ></el-cascader>
      </p>
      <!-- 点击tab栏触发请求 -->
      <el-tabs v-model="activeName" @tab-click="handleCascaderChange">
        <el-tab-pane label="动态参数" name="many"
          ><el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showAddDialog"
            >添加参数</el-button
          >
          <!-- 动态参数的table -->
          <el-table :data="manyTableList" style="width: 100%" border stripe>
            <!-- 扩展列  -->
            <el-table-column type="expand">
              <!-- 遍历具体的属性值 -->
              <template slot-scope="{ row }">
                <el-tag
                  closable
                  @close="handleClose(index, row)"
                  v-for="(item, index) in row.attr_vals"
                  :key="index"
                  >{{ item }}</el-tag
                >
                <!-- 用每行的数据控制和显示存储 -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column
              label="#"
              type="index"
              width="50"
            ></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作" width="320">
              <template slot-scope="{ row }">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(row)"
                  >编辑</el-button
                >

                <el-button type="danger" size="mini" icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only"
          ><el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showAddDialog"
            >添加属性</el-button
          >
          <!-- 静态参数的table -->
          <el-table :data="onlyTableList" style="width: 100%" border stripe>
            <!-- 扩展列  -->
            <el-table-column type="expand">
              <template slot-scope="{ row }">
                <el-tag
                  closable
                  @close="handleClose(index, row)"
                  v-for="(item, index) in row.attr_vals"
                  :key="index"
                  >{{ item }}</el-tag
                >
                <!-- 用每行的数据控制和显示存储 -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column
              label="#"
              type="index"
              width="50"
            ></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作" width="320">
              <template>
                <el-button type="primary" size="mini" icon="el-icon-edit"
                  >编辑</el-button
                >

                <el-button type="danger" size="mini" icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 新增对话框 -->
    <el-dialog
      :title="'新增' + cateTitle"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="handleAddDialogClose"
    >
      <!-- 新增表单 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addRules"
        label-width="80px"
      >
        <el-form-item :label="cateTitle" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParam">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog
      :title="'编辑' + cateTitle"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="handleEditDialogClose"
    >
      <!-- 编辑表单 -->
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item :label="cateTitle" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParam">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      activeName: 'many',
      // 父级分类
      cateList: [],
      // 选中的分类
      selectedKeys: [1, 3, 6],
      manyTableList: [], // 存动态参数列表
      onlyTableList: [], // 存静态参数列表
      addDialogVisible: false, // 是否显示新增对话框
      addForm: { // 表单数据对象
        attr_name: '' // 名称
      },
      addRules: { // 表单校验规则对象
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editDialogVisible: false, // 是否显示编辑对话框
      editForm: { // 表单数据对象
        attr_name: '' // 名称
      },
      editRules: { // 表单校验规则对象
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 控制输入框和按钮的显示
      inputVisible: false,
      // 存储输入框的内容
      inputValue: ''
    }
  },
  // 钩子函数
  created () {
    this.getCateList()
    // 测试代码
    this.getParamsList()
  },
  // 利用计算属性简化模板
  computed: {
    isBtnDisabled () {
      return this.selectedKeys.length !== 3
    },
    cateId () {
      return this.selectedKeys[this.selectedKeys.length - 1]
    },
    cateTitle () {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  },
  methods: {
    async showEditDialog (row) {
      const {
        data: res
      } = await this.$http.get(
        `categories/${row.cat_id}/attributes/${row.attr_id}`,
        { params: { attr_sel: row.attr_sel } }
      )
      console.log(res)
      this.editForm = res.data
      this.editDialogVisible = true
    },
    handleEditDialogClose () {
      // 关闭对话框事件
      this.$refs.editFormRef.resetFields()
    },
    editParam () {
      // 添加属性或分类
      // 校验表单
      this.$refs.editFormRef.validate(async isOk => {
        // 如果校验失败，则退出函数
        if (!isOk) return false
        // 如果成功，则发送异步请求
        const { data: resBody } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        // 如果 添加失败，则返回
        if (resBody.meta.status !== 200) {
          return this.$msg.error(resBody.meta.msg)
        }
        // 如果 添加成功，则重新请求渲染列表
        this.getParamsList()
        // 关闭窗口
        this.editDialogVisible = false
        // 提示消息
        this.$msg.success(resBody.meta.msg)
      })
    },
    showAddDialog () {
      this.addDialogVisible = true
    },
    handleAddDialogClose () {
      // 关闭对话框事件
      this.$refs.addFormRef.resetFields()
    },
    addParam () {
      // 添加属性或分类
      // 校验表单
      this.$refs.addFormRef.validate(async isOk => {
        // 如果校验失败，则退出函数
        if (!isOk) return false
        // 如果成功，则发送异步请求
        const { data: resBody } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        // 如果 添加失败，则返回
        if (resBody.meta.status !== 201) {
          return this.$msg.error(resBody.meta.msg)
        }
        // 如果 添加成功，则重新请求渲染列表
        this.getParamsList()
        // 关闭窗口
        this.addDialogVisible = false
        // 提示消息
        this.$msg.success(resBody.meta.msg)
      })
    },
    handleCascaderChange () {
      if (this.selectedKeys.length < 3) {
        this.selectedKeys = []
        this.manyTableList = []
        this.onlyTableList = []
        return
      }
      this.getParamsList()
    },
    async getCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }
      })
      this.cateList = res.data
    },
    async getParamsList () {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      )
      // 字符串转数组
      res.data.forEach(t => {
        // 如果不为空就做转换，为空就赋值为空数组
        t.attr_vals = t.attr_vals ? t.attr_vals.split(' ') : []
        // 给每一行添加控制显示和存储文本的变量
        t.inputVisible = false
        t.inputValue = ''
      })
      // console.log(res)
      // 标准写法
      // if (this.activeName === 'many') {
      //   this.manyTableList = res.data
      // } else {
      //   this.onlyTableList = res.data
      // }
      // 简化写法
      this[`${this.activeName}TableList`] = res.data
    },
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async handleInputConfirm (row) {
      // const inputValue = this.inputValue
      // 存储本地
      if (row.inputValue.trim()) {
        row.attr_vals.push(row.inputValue)
        // 发送请求
        this.saveAttrs(row)
      } // 解决回车创建两个
      row.inputVisible = false
      // 不管怎样都关闭清空
      row.inputValue = ''
    },
    async saveAttrs (row) {
      await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
    },
    handleClose (index, row) {
      // 删除本地
      row.attr_vals.splice(index, 1)
      // 发送请求
      this.saveAttrs(row)
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
